<?php
/*
Copyright (C) 2009 de Flotte Maxence

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
?>
<?php
/**
 * @author de Flotte Maxence <xamax87@gmail.com>
 * @package std
 * @version 1.0
 */


/**
 * Ajoute des parents à un label
 * Attention cette fonction suppose qu'on a les droits en écriture sur le label
 * @package	std
 * @param	int|array	$lid				Identifiant du label
 * @param	int|array	$_parents		Identifiant des labels parents à ajouter
 * @return	bool								Retourne true en cas de succès, false dans le cas contraire
 */
function addParents($lid,$type,$_parents) {
	
	if(is_int($_parents))
		$_parents = array($_parents);
		
	foreach($_parents AS $key => $label)
		if($key == 0)
			$listLabelParent = $label;
		else
			$listLabelParent .= '|'.$label;
	
	if(!empty($_SESSION['group']))
		foreach($_SESSION['group'] AS $key => $grp)
			if($key == 0)
				$listGroup = $grp;
			else
				$listGroup .= '|'.$grp;
	else
		$listGroup = '';
		
	if(!empty($_SESSION['user']))
		$user = $_SESSION['user'];
	else
		$user = '0';
	
	//On compte le nombre de parents
		$nbParents1 = count($_parents);
	
	$args = array('^'.$listLabelParent.'$',$type)
	
	//Si $user = 0, alors la requête ne regarde que les le champs "other"
		if($user == 0)
			$ssreq = '( A.other = 1 )';
	//Si on vérifie tous le groupe et l'utilisateur
		else {
			$ssreq = '( A.other = 1 OR A.group REGEXP ? OR (A.user = 1 AND L.User = ?)  )';
			$args[] = '^'.$listGroup.'$';
			$args[] = $user;
		}
	
	
	
	$req = 'SELECT count(*) AS count FROM '.$GLOBALS['prefix'].'label AS L inner join '.$GLOBALS['prefix'].'_autocreate_childs_permissions AS A on A.id=L.id WHERE L.id REGEXP ? AND A.type=? AND '.$ssreq.' ;';

	$res = ZzSQL::queryFirst($req,$args);
	if($res != 0)
		$nbParents2 = intval($res['count']);
	else
		$nbParents2 = 0;

	if($nbParents1 != $nbParents2)
		return false;
	
	foreach($_parents as $plid) {
		cleanZzG($plid);
		$req = 'INSERT INTO '.$GLOBALS['prefix'].'_label(id_father, id_son) VALUES(?,?);';
		ZzSQL::exec($req,array($plid,$lid))
	}
	cleanZzG($lid);
	
	return true;
	
}

/**
 * Enlève des parents à un label
 * Attention cette fonction suppose qu'on a les droits en écriture sur le label
 * @package	std
 * @param	int|array	$lid				Identifiant du label
 * @param	int|array	$_parents		Identifiant des labels parents à ajouter
 * @return	bool								Retourne true en cas de succès, false dans le cas contraire
 */
function unlinkParents($lid,$type,$_parents,$force = false) {
	
	//On compte le nombre de parents à enlever
		$nbParents2del = count($_parents);
	//Parmis les parentss à enlever combien peut-on réélement enlever ?
		foreach($_parents AS $key => $label)
			if($key == 0)
				$listLabelParent = $label;
			else
				$listLabelParent .= '|'.$label;
		if(empty($listLabelParent))
			$listLabelParent = '';
	
		if(!empty($_SESSION['group']))
			foreach($_SESSION['group'] AS $key => $grp)
				if($key == 0)
					$listGroup = $grp;
				else
					$listGroup .= '|'.$grp;
		else
			$listGroup = '';
			
		if(!empty($_SESSION['user']))
			$user = $_SESSION['user'];
		else
			$user = '0';

		$args = array('^'.$listLabelParent.'$',$type)
		
		//Si $user = 0, alors la requête ne regarde que les le champs "other"
			if($user == 0)
				$ssreq = '( A.other = 1 )';
		//Si on vérifie tous le groupe et l'utilisateur
			else {
				$ssreq = '( A.other = 1 OR A.group REGEXP ? OR (A.user = 1 AND L.User = ?)  )';
				$args[] = '^'.$listGroup.'$';
				$args[] = $user;
			}
		
		$req = 'SELECT count(*) AS count FROM '.$GLOBALS['prefix'].'label AS L inner join '.$GLOBALS['prefix'].'_autocreate_childs_permissions AS A on A.id=L.id WHERE L.id REGEXP ? AND A.type=? AND '.$ssreq.' ;';
		
		$res = ZzSQL::query($req,$args);
		if($res != null)
			$nbParentsWeCanUnlink = intval($res['count']);
		else
			$nbParentsWeCanUnlink = 0;
	
		if($nbParents2del != $nbParentsWeCanUnlink)
			return false;
	if(!$force) {
		//On compte le nombre de parents
			$req = 'SELECT count(*) AS count FROM '.$GLOBALS['prefix'].'_label  WHERE id_son = ? ;';
			
			$res = ZzSQL::queryFirst($req,array($lid));
			if($res != null)
				$nbParents = intval($res['count']);
			else
				$nbParents = 0;
				
		//Le nombre de parent doit êtrez supérieur aux nombre de parent à enlever
			if($nbParents<=$nbParents2del)
				return false;
	}
	//netoyage des fichier cache
	foreach($_parents as $plid)
		cleanZzG($plid);
	cleanZzG($lid);
	
	//Unlink
		$req = 'DELETE FROM '.$GLOBALS['prefix'].'_label WHERE id_father REGEXP ? AND id_son = ? ;';
		if(ZzSQL:exec($req,array('^'.$listLabelParent.'$',$lid)) == 0)
			return false;
	
	return true;
	
}

//Copy de manageLabel
//Vide les dossiers de cache
function cleanZzG($label,$all = false) {
	
	if($label != null) {
		//On ouvre le fichier log
			//On creer le fichier log si il n'existe pas & on le récupère dans la variable _tree
				if(!file_exists($GLOBALS['cwd'].'/ZzG/tree.log')) {
					$_tree['totalSize'] = 0;
					file_put_contents('./ZzG/tree.log', serialize($_tree));
				}
				else
					$_tree = unserialize(file_get_contents($GLOBALS['cwd'].'/ZzG/tree.log'));

		//
		$path = '';
		if(!is_numeric($label)) {
			$_label = explode('-',$label);
			$label = $_label[0];
			for($i = 1; $i < count($_label);$i++)
				$path .= $_label[$i];
		}

		$addr = $GLOBALS['cwd'].'/ZzG/'.$label;
		//À verifier
		//$addr2 = './ZzG/'.$label;
		if(is_dir($addr)) {
			if($dir = opendir($addr))
				while($file = readdir($dir)) { 
					if($file != '..' and $file !='.' and (preg_match('!^'.$path.'_altPuZZle_(.*)-lang_(.*).php!',$file) or $all)) {
						if(isSet($_tree[$addr2 . '/' . $file])) {
							$_tree['totalSize'] -= filesize($addr . '/' . $file);
							unset($_tree[$addr2 . '/' . $file]);
						}
						unlink($addr . '/' . $file); 
					}
				}
			closedir($dir);
		}
		file_put_contents($GLOBALS['cwd'].'/ZzG/tree.log', serialize($_tree));
	}
}
?>